﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.ComponentModel;
using Deployment.Data.SQL.Helpers;

namespace Deployment.Data.SQL.Connections.UI
{
    /// <summary>
    /// Interaction logic for SQLServerControl.xaml
    /// </summary>
    public partial class SQLServerControl : UserControl
    {
        public SQLServerControl()
        {
            InitializeComponent();
        }


        private void cbo_Servers_DropDownOpened(object sender, EventArgs e)
        {
            cbo_Servers.Cursor = Cursors.Wait;
            refreshServerList();
        }

        private void refreshServerList()
        {
            if (cbo_Servers.ItemsSource == null && btn_refresh.IsEnabled)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += RefreshServerListWorker_DoWork;
                worker.RunWorkerCompleted += RefreshServerListWorker_RunWorkerCompleted;
                btn_refresh.IsEnabled = false;
                worker.RunWorkerAsync();
            }
        }

        void RefreshServerListWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = SQLServerHelpers.FindSQLServers();
        }

        void RefreshServerListWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                List<String> results = e.Result as List<String>;
                if (results != null)
                {
                    cbo_Servers.ItemsSource = results;
                }
            }
            btn_refresh.IsEnabled = true;
            cbo_Servers.Cursor = Cursors.Arrow;
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            cbo_Servers.Cursor = Cursors.Wait;
            refreshServerList();
        }

    }
}
